<?php

namespace App\Jobs;

use App\Constant\JpushCode;
use App\Constant\NewFlowEnum;
use App\Constant\QueueKey;
use App\Constant\SmsTemplate;
use App\Events\JpushNoticeEvent;
use App\Events\LoanRequestRetryEvent;
use App\Events\NewFlowOrderEvent;
use App\Events\UserLoanApplyEvent;
use App\Facades\MoneyPlatformRequestFacade;
use App\Models\LoanApply;
use App\Models\SettingRepayRate;
use App\Models\User;
use App\Models\UserBankCard;
use App\Models\UserLoanRequest;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class LoanApplyLoanJionJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $loan_app;

    public function __construct(LoanApply $loan_app)
    {
        $this->loan_app = $loan_app;
    }

    /**
     * Execute the job.
     * Desc : 处理用户点击放款 把要款参数放进 队列  定时器下午2点开始要款
     * @return void
     */
    public function handle()
    {
        //是否需要推送短信
        $is_send_sms = $this->loan_app->is_send_loan == LoanApply::IS_SEND_SMS;

        //获取用户最新的一条授信成功id
        $loanRequest = UserLoanRequest::where('user_id', $this->loan_app->user_id)
            ->where('status', UserLoanRequest::STATUS_SUCCESS)
            ->where('current', UserLoanRequest::CURRENT_NOW)
            ->select('id', 'user_id', 'channel', 'actually_loan_money', 'actually_period', 'credit_id', 'pre_insurance_amt','cash_card_choice_id')
            ->orderByDesc('id')
            ->first();

        if(empty($loanRequest)) {
            Log::debug('JCFC用户id为' . $this->loan_app->user_id . '的用户没有成功授信记录' . date('Y-m-d H:i:s')  . PHP_EOL);
            return true;
        }

        //获取这个用户
        $user = User::where(['id'=>$this->loan_app->user_id])->first();
        if (empty($user)){
            Log::debug('JCFC用户id为' . $this->loan_app->user_id . '的用户于队列查询失败' . date('Y-m-d H:i:s')  . PHP_EOL);
            return true;
        }


        //获取相关费率
        $getReplyRate = SettingRepayRate::getRateByChannl($loanRequest->channel, $loanRequest->actually_period);

        if (!$getReplyRate) {
            Log::debug('JCFC用户id为' . $this->loan_app->user_id . '的用户于' . date('Y-m-d H:i:s') . '使用Ip地址为' . $this->loan_app->ip . '的设备申请放款时，由于setting_replay_rates表中查询channel_code为(' . $loanRequest->channel . ')，period为（' . $loanRequest->actually_period . '）的数据信息不存在导致放款申请操作失败' . PHP_EOL);
            return true;
        }

        $params = [
            'pre_insurance_amt' => doubleval($loanRequest->pre_insurance_amt / 100),
            'credit_id' => $loanRequest->credit_id,
            'amount' => doubleval($loanRequest->actually_loan_money / 100),
            'period' => $loanRequest->actually_period,
        ];
        $res = MoneyPlatformRequestFacade::applyLoan($params);
        /*$res = [
            'code' => '01',
            'message' => '操作成功',
            'subCode' => 'P',
            'sign' => '',
            'data' => [
                'amount' => 1000,
                'creditId' => 'CR201904030005137886522322005655',
                'loanId' => '100000000000',
                'message' => '',
                'outTradeId' => '20190402868910255505',
                'period' => 3,
                'status' => 'P',
            ]
        ];*/
        Log::debug('「 JCFC用户id为' . $this->loan_app->user_id . '使用授信id为' . $loanRequest->credit_id . '银行卡id为' . $this->loan_app->bank_card_id . '进行放款申请时。资方放款返回值 」' . json_encode($res, JSON_UNESCAPED_UNICODE));

        if (empty($res) || empty($res['code'])) {
            Log::debug('JCFC的放款申请res为空');
            return true;
        }
        if ($res['code'] !== '01') {
            Log::debug('JCFC的放款申请code不等于1');
            return true;
        }
        //开始更新字段
        $out_trade_id = !empty($res['data']['outTradeId']) ? $res['data']['outTradeId'] : '';
        $loan_sign = !empty($res['sign']) ? $res['sign'] : '';
        $message = !empty($res['message']) ? $res['message'] : ''; //返回的信息
        $status = !empty($res['data']['status']) ? $res['data']['status'] : $res['subCode'];



        if (!$status) {
            Log::debug('JCFC用户id=' . $this->loan_app->user_id . '的用户于' . date('Y-m-d H:i:s') . '使用Ip地址为' . $this->loan_app->ip . '的设备申请放款时，对user_loan_requests表中id为' . $this->loan_app->loan_request_id . '的记录，向资方申请放款时资方响应信息中subcode字段和data.status字段都不存在导致此次放款申请操作失败' . PHP_EOL);
            return true;
        }
        $sub_code = $status;
        $loan_status = LoanApply::getLoanStatusByRes($res);
        //费率配置
        /*array (
            'lending_rate' => '0.0805',
            'insurance_rate' => '0.1480',
            'insure_rate' => '0.0050',
            'month_insurance_rate' => '0.0000',
            'manage_rate' => '0.0300',
            'repayment_rate' => '0.0000',
            'fines_rate' => '0.0050',
        );*/

        $lending_rate = $getReplyRate['lending_rate'];
        $insurance_rate = $getReplyRate['insurance_rate'];
        //$insure_rate = $getReplyRate['insure_rate'];
        $month_insurance_rate = $getReplyRate['month_insurance_rate'];
        $manage_rate = $getReplyRate['manage_rate'];
        $repayment_rate = $getReplyRate['repayment_rate'];
        $fines_rate = $getReplyRate['fines_rate'];



        $data = !empty($res['data']) ? $res['data'] : [];
        //新流订单id,还款时使用
        if (!empty($data['loanId'])) {

            $loan_id = $data['loanId'];
        }
        //资方返回的分期数
        if (!empty($data['period'])) {

            $period = $data['period'];
        }
        //资方放款的申请金额
        if (!empty($data['amount'])) {

            $amount = $data['amount'] * 100;
        }

        try {
            LoanApply::where(['loan_request_id'=>$this->loan_app->loan_request_id])->update([
                'loan_id'=> $loan_id,
                'sub_code' => $sub_code,
                'loan_sign' => $loan_sign,
                'loan_status' => $loan_status,
                'amount' => $amount,
                'period' => $period,
                'out_trade_id' => $out_trade_id,
                'message' => $message,
                'lending_rate' => $lending_rate,
                'insurance_rate' => $insurance_rate,
                'month_insurance_rate' => $month_insurance_rate,
                'manage_rate' => $manage_rate,
                'repayment_rate' => $repayment_rate,
                'fines_rate' => $fines_rate,
            ]);

        } catch (\Exception $e) {
            Log::debug('「JCFC申请放款时」由于' . $e->getMessage() . '错误导致放款结果异常');
            return true;
        }

        $applies = LoanApply::where(['loan_request_id'=>$this->loan_app->loan_request_id])->first();

        //更新user_globals表用户流程状态事件
        event(new UserLoanApplyEvent($applies));
        if ($applies->loan_status == LoanApply::LOAN_STATUS_PROCESSING) {
            //任务三分钟后加入队列处理，获取放款处理结果
            // 99 置为放款中  如果$loan_id 为空  不进入队列
            if (!empty($applies->loan_id)){
                GetLoanResultJobQueue::dispatch($applies)->onQueue(QueueKey::QUEUE_GET_LOAN_RESULT)->delay(Carbon::now()->addMinutes(3));
            }

        }

        //只有第一次推送要款  才发送短信  推送信息
        if($is_send_sms) {
            //发送短信 状态 1 已发送
            LoanApply::where(['loan_request_id'=>$this->loan_app->loan_request_id])->update([
                'is_send_loan' => LoanApply::SEND_SMS
            ]);
            //短信推送
            if ($user->valid && SmsTemplate::TEMPLATE_CONFIRM_LOAN_APPLY_SUCCESS) {
                SmsTemplate::send(SmsTemplate::TEMPLATE_CONFIRM_LOAN_APPLY_SUCCESS, $user->phone_num, ['name' => $user->valid->name]);
            }
            //app消息推送
            if (!empty($user->globalStatus) && $user->globalStatus->jpush_registration_id)  {
                event(new JpushNoticeEvent([
                    'title' => '要款成功提醒',
                    'body' => sprintf('您的%s期%s元借款已完成要款操作，请留意款项到账情况。', $loanRequest->actually_period, intval($loanRequest->actually_loan_money / 100)),
                    'audience' => JpushCode::AUDIENCE_TYPE_TWO,
                    'to' => [$user->globalStatus->jpush_registration_id],
                    'extras' => [
                        'jump_type' => 2,
                    ],
                ]));
            }
        }
        //更新new_flow_order表中流程状态
        event(new NewFlowOrderEvent(NewFlowEnum::NewFlowGetMoney, false ,$loanRequest->id, []));
    }
}
